import React from "react";
import { useContext } from "react";
import { useEffect } from "react";
import { useState } from "react";
import { styled } from "@mui/material/styles";
import Chip from "@mui/material/Chip";
import Paper from "@mui/material/Paper";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import SchoolOutlinedIcon from "@mui/icons-material/SchoolOutlined";
import ShowCourse from "./ShowCourse";
import Popover from "@mui/material/Popover";
import Typography from "@mui/material/Typography";
import { GETCOURSE_URL, GETCOURSETIME_URL } from "../../../constants/url";
import Popper from "@mui/material/Popper";
import { TitleContext } from "../../../router";
import { getQueryFn } from "../../../query/getQueryFn";
import { useQuery } from "@tanstack/react-query";
import Loading from "../../../components/loading";
import { useMutation } from "@tanstack/react-query";
import {
  Box,
  Avatar,
  Button,
  FilledInput,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import { mutateQueryFn } from "../../../query/mutateQueryFn";

//课程页面头部，卡片
const chipStyle = ["filled", "outlined"];
const ListItem = styled("li")(({ theme }) => ({
  margin: theme.spacing(0.5),
}));

function ChipsArray(props) {
  //数据处理
  const courseInfo = props.courseInfo;
  const chipAdd = props.chipAdd;
  const [chipData, setChipData] = useState([{ id: 0, label: "我的课程" }]);
  useEffect(() => {
    let chipDataF = chipData;
    courseInfo?.forEach((element, index) => {
      if (element.id) {
        chipDataF.push({ id: element.id, label: element.name });
      }
    });
    setChipData(...[chipDataF]);
  }, []);
  useEffect(() => {
    if (props.chipAdd.id != "") {
      if (props.chipAdd.isAdd == true) {
        handleAdd(props.chipAdd);
        props.setChipAdd({ id: "", label: "", isAdd: false });
      }
    }
  });

  //删除一个卡片
  const handleDelete = (chipToDelete) => () => {
    setChipData((chips) => chips.filter((chip) => chip.id !== chipToDelete.id));
    if (chipToDelete.id == props.courseId) {
      props.handleDelete();
    }
  };
  //添加一个卡片
  const handleAdd = (chipToAdd) => {
    let isAdd = true;
    let chipDataF = chipData;
    chipData?.forEach((element) => {
      if (chipToAdd.id == element.id) {
        isAdd = false;
      }
    });
    if (isAdd == true) {
      chipDataF.push({ id: chipToAdd.id, label: chipToAdd.label });
      setChipData(...[chipDataF]);
    }
    props.handleAdd(chipToAdd.id);
  };

  return (
    <Paper
      sx={{
        flexDirection: "column",
        display: "flex",
        listStyle: "none",
        mt: 1,
        height: "590px",
        paddingTop: 2,
        width: "100%",
        alignItems: "center",
      }}
    >
      <Typography
        variant="h6"
        sx={{
          marginLeft: 3,
          marginBottom: 1,
          marginRight: 1,
          width: 100,
          mt: 1,
        }}
      >
        课程导航
      </Typography>
      {chipData?.map((data) => {
        let icon;

        if (data.label === "我的课程") {
          icon = <SchoolOutlinedIcon />;
        }

        return (
          <ListItem key={data.id} sx={{}}>
            <Chip
              icon={icon}
              sx={{ mt: "3px", width: 170 }}
              label={data.label}
              color="primary"
              // onDelete={
              //   data.label === "我的课程" ? undefined : handleDelete(data)
              // }
              variant={data.id === props.courseId ? chipStyle[0] : chipStyle[1]}
              clickable={true}
              onClick={() => props.onCick(data)}
            />
          </ListItem>
        );
      })}
    </Paper>
  );
}

//课程页面主体，课程表

function BasicTable(props) {
  const rows = props.rows;
  const color = [
    {
      bac: "#fdebdd", //1
      word: "#cf6f5c",
    },
    {
      bac: "#e6f4ff", //2
      word: "#3ba7d5",
    },
    {
      bac: "#defbf7", //3
      word: "#6caead",
    },
    {
      bac: "#eeedff", //4
      word: "#8a86c6",
    },
    {
      bac: "#fcebcd", //5
      word: "#e29e28",
    },
    {
      bac: "#ffeff0", //6
      word: "#bb6d82",
    },
    {
      bac: "#eaf2ff", //7
      word: "#6e8ec2",
    },
    {
      bac: "#ffeef8", //8
      word: "#dc7bb2",
    },
    {
      bac: "#e6f4ff", //9
      word: "#2a9ccd",
    },
    {
      bac: "#fff9c9", //10
      word: "#beb83d",
    },
    {
      bac: "#faedff", //11
      word: "#a26ec2",
    },
    {
      bac: "#f4f2fd", //12
      word: "#7e8bc0",
    },
  ];
  const colors = ["#f9f6f680", "#c9c9c940"];
  // function color(num) {
  //   let r = Math.floor(Math.random() * 255);
  //   let g = Math.floor(Math.random() * 255);
  //   let b = Math.floor(Math.random() * 255);
  //   // let r1= ((num+1/7)*255);
  //   // let g1= ((num-2/7)*255);
  //   // let b1 =((num-3/7)*255);;
  //   let color = "rgba(" + r + "," + g + "," + b + ",0.3)";
  //   return color;
  // }

  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const id = open ? "simple-popper" : undefined;
  const handlePopoverOpen = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const handlePopoverClose = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };
  const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  return (
    <TableContainer component={Paper} sx={{ mt: 1, width: "100%" }}>
      <Table
        sx={{
          minWidth: 650,
          height: "590px",
          border: "1px solid #e1d8d861",
        }}
        aria-label="simple table"
      >
        <TableHead
          sx={{
            height: "80px",
            mt: "5px",
          }}
        >
          <TableRow>
            <TableCell
              sx={{
                border: "1px solid #e1d8d861",
                width: "12%",
                background: colors[1],
              }}
            ></TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期一
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期二
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期三
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期四
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期五
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期六
            </TableCell>
            <TableCell
              align="left"
              sx={{
                border: "1px solid #e1d8d861",
                background: colors[1],
                width: "12%",
              }}
            >
              星期日
            </TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows?.map((row) => (
            <TableRow
              key={row.title}
              // sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
            >
              <TableCell
                component="th"
                scope="row"
                sx={{ border: "1px solid #e1d8d861", background: colors[1] }}
              >
                {row.title}
              </TableCell>
              {row.day?.map((element, index) => (
                <TableCell
                  align="left"
                  onClick={() => props.onCick2(element)}
                  sx={{ border: "1px solid #e1d8d861" }}
                >
                  {element.content == "" ? (
                    element.content
                  ) : (
                    <Paper
                      align="center"
                      sx={{
                        cursor: "pointer",
                        width: "100%",
                        height: "100%",
                        boxShadow: "rgb(0 0 0 / 30%) 0px 3px 2px",
                        // background: color(index),
                        background: color[element.id % 12].bac,
                        color: color[element.id % 12].word,
                        borderRadius: 2,
                      }}
                      // onMouseOver={element.content == ""?undefined:handlePopoverOpen}
                      // onMouseLeave={element.content == ""?undefined:handlePopoverClose}
                    >
                      <span
                        style={{
                          position: "relative",
                          top: "10px",
                          display: "block",
                        }}
                      >
                        {element.content}
                      </span>
                      <span
                        style={{
                          position: "relative",
                          top: "10px",
                          display: "block",
                        }}
                      >
                        {element.location}
                      </span>
                      {/* <Popper id={id} open={open} anchorEl={anchorEl}>
                        <Paper sx={{background: color[index%12].bac,color: color[index%12].word,}}>
                          <Typography sx={{ p: 2 }}>{element.content}</Typography>
                        </Paper>
                      </Popper> */}
                    </Paper>
                  )}
                </TableCell>
              ))}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

//导出的完整类
export default function Course() {
  const [rows, setRows] = useState([
    {
      title: "第一节（01，02小节）",
      day: [
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
      ],
    },
    {
      title: "第二节（03，04小节）",
      day: [
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
      ],
    },
    {
      title: "第三节（05，06小节）",
      day: [
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
      ],
    },
    {
      title: "第四节（07，08小节）",
      day: [
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
        { content: "", label: "", id: "" },
      ],
    },
    {
      title: "第五节（09，10小节）",
      day: [
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
        { content: "", label: "", location: "", id: "" },
      ],
    },
  ]);

  //获取所有课程
  const {
    data: courses,
    isLoading: getLoading1,
    mutate: getMutate1,
    isSuccess: getSuccess1,
  } = useMutation(["getCourse"], mutateQueryFn);
  //获取课程表
  const {
    data: times,
    isLoading: getLoading2,
    mutate: getMutate2,
    isSuccess: getSuccess2,
  } = useMutation(["getCourseTime"], mutateQueryFn);

  useEffect(() => {
    getMutate1({ url: GETCOURSE_URL, method: "get", useToken: true });
  }, []);
  useEffect(() => {
    getMutate2({ url: GETCOURSETIME_URL, method: "get", useToken: true });
  }, []);
  const [courseInfo1, setCourseInfo1] = useState();
  const [courseTime, setCourseTime] = useState([]);
  useEffect(() => {
    if (getSuccess1) {
      setCourseInfo1(
        courses.data.data?.map((val, key) =>
          val.status === 1
            ? {
                ...val,
              }
            : {}
        )
      );
    } else {
    }
  }, [courses]);
  useEffect(() => {
    if (getSuccess2) {
      setCourseTime(
        times.data.data?.map((val, key) =>
          val.id !== undefined
            ? {
                id: val.id,
                weeks: val.time.weeks,
              }
            : {}
        )
      );
      dataHandle(times.data.data, rows);
    } else {
    }
  }, [times]);

  const [open, setOpen] = useState(true);
  const [courseId, setCourseId] = useState(0);
  const [chipAdd, setChipAdd] = useState({ id: "", label: "", isAdd: false });

  function dataHandle(courseT, rows) {
    let rowsF = rows;
    courseT?.forEach((item, index1) => {
      item.time.weekday?.forEach((element, index) => {
        switch (element) {
          case 1:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 2:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 3:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 4:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 5:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 6:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          case 7:
            rowsF[item.time.order[index] - 1].day[element - 1] = {
              content: item.name,
              location: item.location,
              label: item.name,
              id: item.id,
            };
            break;
          default:
        }
      });
    });
    setRows([...rowsF]);
  }

  //卡片点击事件
  function handleClick(data) {
    if (data.label == "我的课程") {
      setOpen(true);
    } else {
      setOpen(false);
    }
    setCourseId(data.id); //专门为点击卡片后的组件传入一个课程id，这样就能每次唯一渲染这个课程的信息
    getMutate1({ url: GETCOURSE_URL, method: "get", useToken: true });
  }
  //课表点击事件
  function handleClick2(data) {
    if (data.id !== "") {
      let dataF = {
        id: data.id,
        label: data.label,
        isAdd: true,
      };
      setChipAdd(dataF);
    }
  }

  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(3);
  }, []);
  return (
    <div>
      {(getLoading1 || getLoading2) && (
        <Box
          sx={{
            width: "100%",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            minHeight: 600,
          }}
        >
          <Loading />
        </Box>
      )}
      {/*display: "flex", float: "left", */}
      {getSuccess1 && getSuccess2 && (
        <Grid container spacing={2}>
          <Grid item xs={12} md={10}>
            <div id="courseBody">
              {open === true ? (
                <BasicTable
                  rows={rows}
                  onCick2={(data) => handleClick2(data)}
                ></BasicTable>
              ) : (
                <ShowCourse
                  courseId={courseId}
                  courseInfo={courseInfo1}
                  courseTime={courseTime}
                ></ShowCourse>
              )}
            </div>
          </Grid>
          <Grid item xs={12} md={2}>
            <div id="courseHead">
              <ChipsArray
                onCick={(data) => handleClick(data)}
                handleDelete={() => {
                  setOpen(true);
                  setCourseId(0);
                }} //在删除一张卡片之后，回到课程表
                handleAdd={(value) => {
                  setOpen(false);
                  setCourseId(value);
                }}
                setChipAdd={(data) => setChipAdd(data)}
                courseInfo={courseInfo1}
                courseId={courseId}
                chipAdd={chipAdd}
              ></ChipsArray>
            </div>
          </Grid>
        </Grid>
      )}
    </div>
  );
}
